<template>
  <div class="warp-box  clearfix">
    <div class="warp-con">
      <div class="header">
        <div class="headerWrapper">
          <div class="search">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item>
                <el-input v-model="name" placeholder="请输入角色名称" @keyup.enter.native="query" auto-complete="off" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="query">查询</el-button>
                <el-button type="primary" @click="addRole">新增</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="content">
        <el-table :data="tableData" :header-row-style="HeaderStyle" :row-style='cellStyle' border stripe
          :tooltip-effect="'dark'" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-table-column align="center" prop="name" show-overflow-tooltip label="角色名称" />
          <el-table-column align="center" prop="userNames" show-overflow-tooltip label="所属人员">
            <template slot-scope="scope">
              <span>{{ scope.row.userNames !=null? scope.row.userNames.join(',') : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="sortNo" show-overflow-tooltip label="排序" />
          <el-table-column align="center" prop="remark" show-overflow-tooltip label="备注" />
          <el-table-column label="操作" align="center" min-width="130">
            <template slot-scope="scope">
              <span @click="showMenu(scope.row)" class="pointer">菜单权限</span>
              <i class="line"></i>
              <span @click="updateRole(scope.row)" class="pointer">修改</span>
              <i class="line"></i>
              <span @click="deleteRole(scope.row)" class="pointer">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-sizes="[10]" :page-size="this.pageSize" :current-page="pageIndex" :total="totalCount"
                       @current-change="pager" background layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </div>

    <el-dialog :visible.sync="roleVisible" :title="formTitle" :before-close="cancel" :close-on-click-modal="false"
      :width="'30%'">
      <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" class="input" auto-complete="off" />
        </el-form-item>
        <el-form-item label="所属用户" prop="userIds">
          <el-select v-model="roleForm.userIds" @focus="showUser" ref="selectUser" multiple clearable>
            <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number v-model="roleForm.sortNo" :min="1" class="input" auto-complete="off" />
        </el-form-item>
        <el-form-item class="full-width-form-2" label="备注" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 5}" v-model="roleForm.remark" auto-complete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveRole" class="dialogBtn">保 存</el-button>
        <el-button type="primary" @click="cancel" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="userVisible" title="用户列表" :before-close="cancelUser" :close-on-click-modal="false">
      <div class="search">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <SelectTree :options="departmentData" :clearable="true" :accordion="false" :value="departmentId"
              :placeholder="'请选择部门'" @getValue="getValue($event)" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="userName" class="input" placeholder="请输入用户名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="upload" @click="findPageUser">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="forms">
        <el-table border stripe ref="userTable" :data="userTableData" @select="handleSelection" @select-all="handleSelectionAll">
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column align="center" prop="name" show-overflow-tooltip label="真实姓名" />
          <el-table-column align="center" prop="account" show-overflow-tooltip label="登录名" />
          <el-table-column align="center" prop="departName" show-overflow-tooltip label="部门" />
        </el-table>
      </div>
      <div class="footer">
        <div class="paging info">
          <el-pagination :page-sizes="[8]" :page-size="userSize" :current-page="userIndex" :total="userTotalCount"
            @current-change="pagerUser" background layout="total, sizes, prev, pager, next" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUserIds" class="dialogBtn">保 存</el-button>
        <el-button type="primary" @click="cancelUser" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="菜单权限" :width="'20%'" :visible.sync="menuVisible" :before-close="cancelMenu">
      <el-form class="demo-ruleForm">
        <el-row>
          <el-tree :data="menuData" show-checkbox node-key="id" ref="tree" highlight-current :check-strictly="true"
            :default-checked-keys="selectMenuIds" :props="defaultProps" @check="handleNodeClick">
          </el-tree>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveMenuPermission" class="dialogBtn">保 存</el-button>
        <el-button type="primary" @click="cancelMenu" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import roleApi from '@/api/roleApi'
  import systemApi from '@/api/systemApi'
  import menuApi from '@/api/menuApi'
  import SelectTree from '@/components/TreeSelect'

  export default {
    components: {
      SelectTree
    },
    data() {
      return {
        loading: false,
        name: null,
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        tableData: [],
        cellStyle: {
          height: '60px',
          fontSize: '16px'
        },
        HeaderStyle: {
          height: '70px',
          fontSize: '16px'
        },
        roleForm: {},
        rules: {
          name: [{
            required: true,
            message: '角色名称',
            trigger: 'blur'
          }]
        },
        formEdit: null,
        formTitle: null,
        roleVisible: false,
        userName: null,
        departmentId: null,
        departmentData: [],
        userVisible: false,
        userIndex: 1,
        userSize: 8,
        userTotalCount: 0,
        userTableData: [],
        userOptions: [],
        selectedUserIds: [],
        roleId: null,
        menuData: [],
        defaultProps: {
          id: 'id',
          label: 'name'
        },
        selectMenuIds: [],
        menuVisible: false
      }
    },
    created() {
      this.findPage()
    },
    methods: {
      query() {
        this.pageIndex = 1;
        this.findPage();
      },
      pager(val) {
        this.pageIndex = val
        this.findPage()
      },
      findPage() {
        this.loading = true
        let params = {
          name: this.name,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          sort: 'sortNo',
          order: 'ASC'
        }
        roleApi.findRolePage(params).then(res => {
          this.loading = false
          let result = res.data.result
          if (res.data.message === 'success' && result) {
            this.tableData = result.rows
            this.totalCount = result.totalCount
          } else {
            this.tableData = []
            this.totalCount = 0
          }
        })
      },
      addRole() {
        this.formEdit = 'add'
        this.formTitle = '新增角色'
        this.findUser()
        this.roleVisible = true
      },
      updateRole(row) {
        this.formEdit = 'edit'
        this.formTitle = '修改角色'
        this.findUser()
        roleApi.getRoleInfo(row.id).then(res => {
          if (res.data.message === 'success') {
            this.roleForm = res.data.result
            this.roleVisible = true
          }
        })
      },
      saveRole() {
        this.$refs['roleForm'].validate((valid) => {
          if (valid) {
            this.showLoading('正在保存')
            let response
            let params = Object.assign({}, this.roleForm)
            if (this.formEdit === 'add') {
              response = roleApi.addRole(params)
            } else {
              response = roleApi.updateRole(params)
            }
            response.then(res => {
              this.hideLoading()
              if (res.data.message === 'success') {
                this.findPage()
                this.cancel()
                this.$notify({
                  title: '消息',
                  message: ('保存成功!'),
                  position: 'bottom-right',
                  showClose: false,
                  type: 'success'
                })
              } else {
                this.$notify.error({
                  title: '消息',
                  message: '保存失败'
                })
              }
            })
          } else {
            return false
          }
        })
      },
      deleteRole(row) {
        let tips = ''
        let deptId = row.id
        if (row) {
          tips = `此操作将删除: ${row.name}, 是否继续?`
        } else {
          return
        }
        this.$confirm(tips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roleApi.deleteRole(deptId).then((res) => {
            if (res.data.message === 'success') {
              this.$notify({
                title: '消息',
                message: ('删除成功！'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              this.findPage()
            } else {
              this.$notify.error({
                title: '消息',
                message: '删除失败'
              })
            }
          })
        }).catch((error) => {
          console.log(error)
        })
      },
      cancel() {
        this.roleForm = {}
        this.roleVisible = false
      },
      findDepartment() {
        this.departmentData = []
        systemApi.getDeparmentList().then(res => {
          if (res.data.message === 'success') {
            this.departmentData = res.data.result
          }
        })
      },
      showUser() {
        this.$refs.selectUser.blur()
        this.findPageUser()
        this.findDepartment()
        this.userVisible = true
      },
      findPageUser() {
        let params = {
          name: this.userName,
          departmentId: this.departmentId,
          pageIndex: this.userIndex,
          pageSize: this.userSize
        }
        this.selectedUserIds = this.roleForm.userIds
        systemApi.findPageUser(params).then(res => {
          let result = res.data.result
          if (res.data.message === 'success' && result) {
            this.userTableData = result.rows
            this.userTotalCount = result.totalCount
            if (this.selectedUserIds && this.selectedUserIds.length > 0) {
              this.$nextTick(() => {
                this.userTableData.forEach(user => {
                  if (this.selectedUserIds.indexOf(user.id) > -1) {
                    this.$refs.userTable.toggleRowSelection(user, true)
                  }
                })
              })
            }
          } else {
            this.userTableData = []
            this.userTotalCount = 0
          }
        })
      },
      pagerUser(val) {
        this.userIndex = val
        this.findPageUser()
      },
      cancelUser() {
        this.userIndex = 1
        this.userName = null
        this.departmentId = null
        this.userTotalCount = 0
        this.userTableData = []
        this.selectedUserIds = []
        this.userVisible = false
      },
      getValue(value) {
        this.departmentId = value
      },
      handleSelection(selection, row) {
        let id = row.id
        let index = this.selectedUserIds.indexOf(id)
        if (index < 0) {
          this.selectedUserIds.push(id)
        } else {
          this.selectedUserIds.splice(index, 1)
        }
      },
      handleSelectionAll(selection) {
        if (selection.length > 0) {
          selection.forEach((item) => {
            if (this.selectedUserIds.indexOf(item.id) < 0) {
              this.selectedUserIds.push(item.id)
            }
          })
        } else {
          this.userTableData.forEach((item) => {
            this.selectedUserIds.splice(this.selectedUserIds.indexOf(item.id), 1)
          })
        }
      },
      saveUserIds() {
        this.roleForm.userIds = this.selectedUserIds
        this.cancelUser()
      },
      findUser() {
        this.userOptions = []
        roleApi.findUserList().then((res) => {
          if (res.data.message === 'success') {
            this.userOptions = res.data.result
          }
        })
      },
      showMenu(row) {
        this.roleId = row.id
        this.findMenu()
        this.findRoleMenu()
        this.menuVisible = true
      },
      cancelMenu() {
        this.roleId = null
        this.menuData = []
        this.selectMenuIds = []
        this.menuVisible = false
      },
      findMenu() {
        this.menuData = []
        menuApi.findMenu().then((res) => {
          if (res.data.message === 'success') {
            this.menuData = res.data.result
          }
        })
      },
      findRoleMenu() {
        this.selectMenuIds = []
        menuApi.findRoleMenu({
          roleId: this.roleId
        }).then((res) => {
          if (res.data.message === 'success') {
            this.selectMenuIds = res.data.result
          }
        })
      },
      checkedNodes(nodes, checked) {
        if (nodes && nodes.length > 0) {
          nodes.forEach(item => {
            let data = item.data
            let node = this.$refs.tree.getNode(data.id)
            node.setChecked(checked)
            this.checkedNodes(node.childNodes, checked)
          })
        }
      },
      checkedParentNode(data) {
        if (data && data.parentId) {
          let pNode = this.$refs.tree.getNode(data.parentId)
          pNode.setChecked(true)
          this.checkedParentNode(pNode.data, true)
        }
      },
      handleNodeClick(data) {
        let node = this.$refs.tree.getNode(data.id)
        let checked = node.checked
        let childNodes = node.childNodes
        if (childNodes.length > 0) {
          this.checkedNodes(childNodes, checked)
        }
        if (checked) {
          this.checkedParentNode(data)
        }
      },
      saveMenuPermission() {
        let menuIds = this.$refs.tree.getCheckedKeys()
        this.showLoading('正在保存')
        menuApi.saveRoleMenu({
          roleId: this.roleId,
          menuIds: menuIds
        }).then((res) => {
          this.hideLoading()
          if (res.data.messageType === '0') {
            this.$notify({
              title: '消息',
              message: ('保存成功!'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
            this.cancelMenu()
          } else {
            this.$notify.error({
              title: '消息',
              message: '保存失败'
            })
          }
        })
      },
      showLoading(message) {
        this.$loading({
          lock: true,
          text: message,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },
      hideLoading() {
        this.$loading().close()
      }
    }
  }
</script>
<style lang="less" scoped>
  .search {
    & /deep/ .el-form-item__label {
      font-size: 1.8rem;
    }
  }

  /deep/ .el-transfer-panel {
    background: transparent;
  }

  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }

  .el-transfer-panel {
    background: #33a1bf;
  }

  .footer {
    margin-top: 40px;
    color: #ffffff;
    font-size: 16px;

    .info {
      .select {
        width: 52px;
        height: 35px;
      }

      .select /deep/ .el-input__inner {
        padding-left: 5px;
        padding-right: 0;
      }

      .select /deep/ .el-input__icon {
        width: 15px;
      }

      .select /deep/ .el-select__caret {
        /*transform:rotate(270deg);*/
        /*color: black;*/
      }

      .select /deep/ .el-select__caret.is-reverse {}
    }

    .paging {
      /*background-color: pink;*/
      text-align: right;
      padding-right: 30px;
      margin-top: -20px;

      & /deep/ .el-pagination.is-background .btn-prev {
        background: none;
        border: 1px solid rgba(0, 255, 255, 1);
      }

      & /deep/ .el-pagination.is-background .btn-next {
        background: none;
        border: 1px solid rgba(0, 255, 255, 1);
      }

      & /deep/ .el-pager li {
        background: none;
        border: 1px solid rgba(0, 255, 255, 1);
      }

      & /deep/ .el-pagination__total,
      & /deep/ .el-pagination__sizes {
        float: left;
        font-size: 1.6rem;
        height: 35px;
        line-height: 35px;
      }

      & /deep/ .el-input__inner {
        /*width:52px;*/
        height: 35px;
      }

      & /deep/ .el-input .el-input__inner {
        padding-right: 20px;
        color: #FFFFFF;
        font-size: 1.6rem;
      }
    }
  }

  .content {
    margin-top: 10px;

    & /deep/ .el-checkbox__inner {
      height: 20px;
      width: 20px;
      font-size: 28px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      background: none;
    }

    & /deep/ .el-tooltip__popper {
      background-color: red;
    }

    & /deep/ .el-checkbox__inner::after {
      border-width: 2px;
      height: 6px;
      left: 6px;
      top: 3px;
      width: 4px;
    }

    & /deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
      top: 8px;
      background: white;
    }
  }

  .line {
    display: inline-flex;
    height: 21px;
    width: 1px;
    background: rgba(0, 255, 255, 1);
    margin: 0 10px;
    vertical-align: middle;
  }

  .dialogBtn {
    font-size: 1.6rem;

    &:hover {
      background: rgba(12, 161, 151, 1);
    }
  }
</style>
<style lang="less">
  /**
   * 修改样式   覆盖默认的饿了么全局样式
   */
  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }
</style>
